package com.tiantianyuegou.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.StringUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.TooManyListenersException;

/**
 * 添加银行卡
 */
public class AddCardActivity extends BaseActivity implements View.OnClickListener, TextWatcher {

    private ImageView img_title;
    private TextView text_title;
    private EditText edit_card_id, add_edit_user, add_edit_user_id, add_edit_number, edt_getcode;
    private Button btn_getcode, btn_submit;
    private String TAG = "AddCardActivity";
    private TimeCount time;
    private String number, twId;
    private LoadingDialog loadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_card);
        init();
        Tools.changeSystemBar(this);
    }

    @Override
    public void findViewByIds() {

    }

    @Override
    public void initListener() {


    }

    @Override
    public void initData() {

    }

    private void init() {
        text_title = (TextView) findViewById(R.id.text_title);
        img_title = (ImageView) findViewById(R.id.img_title);

        text_title.setText(R.string.add_title);
        img_title.setOnClickListener(this);

        edit_card_id = (EditText) findViewById(R.id.edit_card_id);
        add_edit_user = (EditText) findViewById(R.id.add_edit_user);
        add_edit_user_id = (EditText) findViewById(R.id.add_edit_user_id);
        add_edit_number = (EditText) findViewById(R.id.add_edit_number);
        edt_getcode = (EditText) findViewById(R.id.edt_getcode);

        edit_card_id.addTextChangedListener(this);
        add_edit_user.addTextChangedListener(this);
        add_edit_user_id.addTextChangedListener(this);
        add_edit_number.addTextChangedListener(this);
        edt_getcode.addTextChangedListener(this);


        btn_getcode = (Button) findViewById(R.id.btn_getcode);
        btn_submit = (Button) findViewById(R.id.btn_submit);

        btn_getcode.setOnClickListener(this);
        btn_submit.setOnClickListener(this);


        number = getIntent().getStringExtra("number");
        twId = getIntent().getStringExtra("twId");
        edit_card_id.setText(number);
        time = new TimeCount(this, 60000, 1000);
        loadingDialog=new LoadingDialog(this);
    }

    /**
     * 添加银行卡
     */
    private void loadAddBank() {
        String number = edit_card_id.getText().toString();
        String name = add_edit_user.getText().toString();
        String idcard = add_edit_user_id.getText().toString();
        String phone = add_edit_number.getText().toString();
        String value = edt_getcode.getText().toString();

        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("number", number);
        params.addBodyParameter("name", name);
        params.addBodyParameter("idcard", idcard);
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("value", value);
        params.addBodyParameter("wordId", twId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.ADD_BANK, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response = responseInfo.result;
                Log.e(TAG, "addbank     " + response);
                try {
                    JSONObject object = new JSONObject(response);
                    String code=object.getString("code");
                    if("100".equals(code)){
                        setResult(RESULT_OK);
                        finish();
                    }else{
                        showMsg(object.getString("message"));
                    }
                    if ("100".equals(object.getString("code"))) {
                        setResult(RESULT_OK);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showMsg("解析异常");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    private void getCode() {
        String phoneNum = add_edit_number.getText().toString();
        if (TextUtils.isEmpty(phoneNum)) {
            showMsg("请输入手机号码");
            return;
        } else if (!StringUtils.checkPhone(phoneNum)) {
            showMsg("手机号码格式错误");
            return;
        } else {
            loadCode();
        }
    }

    /**
     * 获取验证码
     */
    private void loadCode() {

        loadingDialog.setMsg("正在获取");
        loadingDialog.showDialog();
        RequestParams params = new RequestParams();
        System.out.println("---------------" + add_edit_number.getText().toString());
        params.addBodyParameter("phone", add_edit_number.getText().toString());
        params.addBodyParameter("type", "3");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GET_CODE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                loadingDialog.dismiss();
                String response = responseInfo.result;
                Log.e(TAG, "code     " + response);
                try {
                    JSONObject object = new JSONObject(response);
                    showMsg(object.getString("message"));
                    String code = object.getString("code");
                    if (code.equals("100")) {
                        time.start();
                    } else if (code.equals("104")) {
                        showMsg("账号未注册");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_title:
                finish();
                break;

            case R.id.btn_getcode:

                getCode();
                break;

            case R.id.btn_submit:
                loadAddBank();

                break;
            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String number = edit_card_id.getText().toString();
        String name = add_edit_user.getText().toString();
        String idcard = add_edit_user_id.getText().toString();
        String phone = add_edit_number.getText().toString();
        String value = edt_getcode.getText().toString();
        if (number != null && !"".equals(number) && name != null && !"".equals(name) && phone != null && !"".equals(phone) && idcard != null && !"".equals(idcard) && value != null && !"".equals(value)) {
            btn_submit.setEnabled(true);
            btn_submit.setAlpha(1.0f);
        } else {
            btn_submit.setEnabled(false);
            btn_submit.setAlpha(0.5f);
        }
    }

    /**
     * 时间计时类
     */
    class TimeCount extends CountDownTimer {
        Activity activity;

        public TimeCount(Activity activity, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.activity = activity;
        }

        /**
         * 计时过程
         *
         * @param millisUntilFinished
         */
        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {
            btn_getcode.setClickable(false);
            btn_getcode.setEnabled(false);
            btn_getcode.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_timecount_bg));
            btn_getcode.setTextColor(getResources().getColor(R.color.textcolor_3));
            btn_getcode.setText(millisUntilFinished / 1000 + "S后重发");
        }

        /**
         * 计时完毕时触发
         */
        @SuppressLint("NewApi")
        @Override
        public void onFinish() {
            btn_getcode.setText(R.string.register_get_code);
            btn_getcode.setClickable(true);
            btn_getcode.setEnabled(true);
            btn_getcode.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_bg));
            btn_getcode.setTextColor(getResources().getColor(R.color.bg_button_normal));

        }
    }
}
